package com.app.business.service;

import com.app.business.model.NoHouseWorkerApply;
import com.app.business.model.Wage;
import com.app.business.model.WorkerInfo;
import com.app.system.jpa.JpaBaseDao;
import com.app.system.jpa.PageBean;
import com.app.system.jpa.Wrapper;
import com.app.system.permission.model.UserInfo;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.WebUtils;
import com.app.system.utils.dataType.BigDecimalUtils;
import com.app.system.utils.dataType.DateUtils;
import com.app.system.utils.dataType.StringUtils;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;


/**
 * Created by zt on 2021-06-24
 */
@Service
public class NoHouseWorkerApplyService extends JpaBaseDao<NoHouseWorkerApply, Integer> {
    @Autowired
    private WorkerInfoService workerInfoService;
    @Autowired
    private OperationService operationService;

    /**
     * 根据workId获取数据
     *
     * @param noHouseWorkerApplyId
     * @return
     */
    public NoHouseWorkerApply getNoHouseWorkerApplyByApplyId(int noHouseWorkerApplyId) {
        StringBuffer hql = new StringBuffer(" from NoHouseWorkerApply n left join fetch n.workerInfo w where n.id = :noHouseWorkerApplyId order by n.id desc");
        LinkedHashMap<String, Object> map = Maps.newLinkedHashMap();
        map.put("noHouseWorkerApplyId", noHouseWorkerApplyId);
        List<NoHouseWorkerApply> list = this.findHql(hql.toString(), map);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 根据workId获取数据
     *
     * @param workerInfoId
     * @return
     */
    public NoHouseWorkerApply getNoHouseWorkerApplyByWorkId(int workerInfoId) {
        StringBuffer hql = new StringBuffer(" from NoHouseWorkerApply n where n.workerInfo.id = :workerInfoId order by n.id desc");
        LinkedHashMap<String, Object> map = Maps.newLinkedHashMap();
        map.put("workerInfoId", workerInfoId);
        List<NoHouseWorkerApply> list = this.findHql(hql.toString(), map);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 分页数据（基础数据列表）
     */
    public PageBean<NoHouseWorkerApply> getWorkerInfoPage(PageBean pageBean) {
        UserInfo userInfo=WebUtils.getLoginUserInfo();
        String departmentCode=userInfo.getDepartment().getCode();
        String joinWorkingDate_ge = (String) WebUtils.getRequest().getParameter("joinWorkingDate_ge");
        String joinWorkingDate_le = (String) WebUtils.getRequest().getParameter("joinWorkingDate_le");
        String retireDate_ge = (String) WebUtils.getRequest().getParameter("retireDate_ge");
        String retireDate_le = (String) WebUtils.getRequest().getParameter("retireDate_le");
        String depCode = (String) WebUtils.getRequest().getParameter("depCode");
        //查询语句
        StringBuffer query = new StringBuffer(" n from NoHouseWorkerApply n left join fetch n.workerInfo w");
        //默认排序(PageBean指定排序字段类型的话，则默认排序不使用)
        StringBuffer orderBy = new StringBuffer("w.id desc");

        Wrapper wrapper = new Wrapper(pageBean,query, null,orderBy);
        wrapper.andLike("w.departmentCode",departmentCode);
        if (StringUtils.isNotEmpty(joinWorkingDate_ge)) {
            Date date = DateUtils.stringToDateFormat(joinWorkingDate_ge, "yyyy-MM-dd");
            wrapper.andGe("w.joinWorkingDate", date);
        }
        if (StringUtils.isNotEmpty(joinWorkingDate_le)) {
            Date date = DateUtils.stringToDateFormat(joinWorkingDate_le, "yyyy-MM-dd");
            wrapper.andLe("w.joinWorkingDate", date);
        }
        if (StringUtils.isNotEmpty(retireDate_ge)) {
            Date date = DateUtils.stringToDateFormat(retireDate_ge, "yyyy-MM-dd");
            wrapper.andGe("w.retireDate", date);
        }
        if (StringUtils.isNotEmpty(retireDate_le)) {
            Date date = DateUtils.stringToDateFormat(retireDate_le, "yyyy-MM-dd");
            wrapper.andLe("w.retireDate", date);
        }
        if (StringUtils.isNotEmpty(depCode)) {
            wrapper.andLike("w.departmentCode", depCode);
        }
        wrapper.initSearchParams();
        return this.pageHql(wrapper);
    }

    /**
     * 保存无房申报表记录
     * @param request
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public synchronized Response saveData(HttpServletRequest request) {
        int noHouseApplyId = ParamUtils.getInt(request, "noHouseApplyId", 0);
        int workerId = ParamUtils.getInt(request, "workerId", 0);
        Precondition.checkAjaxArguement(workerId != 0, "1111", "数据错误，请重试！");
        WorkerInfo workerInfo = workerInfoService.findOne(workerId);
        int operateType=2;
        NoHouseWorkerApply noHouseWorkerApply = this.findOne(noHouseApplyId);
        if (noHouseWorkerApply == null) {
            operateType=1;
            noHouseWorkerApply = new NoHouseWorkerApply();
        }
        WebUtils.bind(request, noHouseWorkerApply);
        noHouseWorkerApply.setWorkerInfo(workerInfo);
        this.save(noHouseWorkerApply);
        //操作记录
        operationService.getOperationHisLog(workerInfo.getName(),noHouseWorkerApply.getId(),operateType,2,noHouseWorkerApply);
        return new Response("0001", "更新成功");
    }


    public NoHouseWorkerApply getNoHouseWorkerInfoByIdCard(String idCard) {
        String hql = " from NoHouseWorkerApply w where w.idCard=:idCard order by w.id asc";
        Map<String, Object> map = Maps.newLinkedHashMap();
        map.put("idCard", idCard);
        List<NoHouseWorkerApply> list = this.findHql(hql.toString(), map);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    public  Map<Integer,NoHouseWorkerApply> getNoHouseWorkerApplyByIdMap(){
        List<NoHouseWorkerApply> noHouseWorkerApplyList=this.findAll();
        Map<Integer,NoHouseWorkerApply> resultMap=new HashMap<>();
        for (NoHouseWorkerApply noHouseWorkerApply:noHouseWorkerApplyList){
            resultMap.put(noHouseWorkerApply.getWorkerInfo().getId(),noHouseWorkerApply);
        }
        return resultMap;
    }
    /**
     * 统计
     */
    public  Map<String,Map<String,String>> getNumAndMoneyByRecord(){
        String sql="select w.record_no as recordNo,count(w.id) as personCount,sum(n.total_subsidy) as money from no_house_worker_apply n,worker_info w where w.id=n.worker_info_id group by w.record_no";
        Map map=new HashMap();
        List<Map> mapList= this.findSql(sql,map);
        Map<String,Map<String,String>> resultMap=new HashMap<>();
        int personNum=0;
        BigDecimal money=new BigDecimal("0");
        for (Map map1:mapList){
            personNum+=Integer.valueOf(map1.get("personCount").toString());
            money=BigDecimalUtils.getSum(money,new BigDecimal(map1.get("money").toString()));
            String recordNo=map1.get("recordNo").toString();
            Map map2=new HashMap();
            map2.put("personCount",map1.get("personCount").toString());
            map2.put("money",map1.get("money").toString());
            resultMap.put(recordNo,map2);
        }
        Map<String, String> map3=new HashMap<>();
        map3.put("personCount",String.valueOf(personNum));
        map3.put("money",String.valueOf(money));
        resultMap.put("hj",map3);
        return resultMap;
    }
}
